package com.d.lib.ui.view.stroke;

import ohos.agp.components.AttrHelper;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.Rect;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;

/**
 * 镂空背景
 * Created by D on 2017/3/15.
 */
public class HoleBgView extends Component implements Component.DrawTask,
    Component.EstimateSizeListener {
  private int mWidth;
  private int mHeight;

  private Rect mRect;
  private RectFloat mRectF;
  private Paint mPaint;
  private int mOffsetX; // 偏移
  private int mOffsetY; // 偏移
  private int mWithrH;
  private int mWithrW;
  private float mStrokeWidth;

  public HoleBgView(Context context) {
    super(context);

    init(context);
  }

  public HoleBgView(Context context, AttrSet attrs) {
    super(context, attrs);

    init(context);
  }

  public HoleBgView(Context context, AttrSet attrs, String defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
  }

  public HoleBgView(Context context, AttrSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
  }

  private void init(Context context) {
    mOffsetX = AttrHelper.fp2px(136.5f, context);
    mOffsetY = AttrHelper.fp2px(29.5f, context);
    mWithrH = AttrHelper.fp2px(35000, context);
    mWithrW = AttrHelper.fp2px(35014.3f, context);
    mStrokeWidth = mWithrH * 2 - AttrHelper.fp2px(34.5f, context);
    mRect = new Rect();
    mRectF = new RectFloat();
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setStyle(Paint.Style.STROKE_STYLE);
    mPaint.setStrokeWidth(mStrokeWidth);
    mPaint.setColor(Color.BLACK);
    mPaint.setAlpha(0.8f);

    setEstimateSizeListener(this::onEstimateSize);
    addDrawTask(this::onDraw);
  }

  @Override
  public void onDraw(Component component, Canvas canvas) {
    int offsetYF = mHeight - mOffsetY;
    int left = mOffsetX - mWithrW;
    int top = offsetYF - mWithrH;
    int right = mOffsetX + mWithrW;
    int bottom = offsetYF + mWithrH;
//        mRect.set(left, top, right, bottom);
    mRectF = new RectFloat(left, top, right, bottom);
    canvas.drawRoundRect(mRectF, mWithrH, mWithrH, mPaint); // 在原有矩形基础上，画成圆角矩形
  }

  @Override
  public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
    mWidth = EstimateSpec.getSize(widthMeasureSpec);
    mHeight = EstimateSpec.getSize(heightMeasureSpec);
    setEstimatedSize(EstimateSpec.getSizeWithMode(mWidth, EstimateSpec.PRECISE),
        EstimateSpec.getSizeWithMode(mHeight, EstimateSpec.PRECISE));
    return true;
  }
}